package com.tencent.cloud.uikit.ui.drawable;

import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.Drawable;

/**
 * 扇形裁剪资源
 *
 * 通过 {@link #setLevel(int)} 自动处理扇形角度，最高等级为 1000
 *
 * @author showxiao
 * @date 2018/8/11
 */
public class SectorDrawable extends ClipDrawable {

    /** 参考自 ClipDrawable.MAX_LEVEL */
    public static final int MAX_LEVEL = 10000;
    private static final float START_ANGLE = 180.0f;
    private static final float TOTAL_ANGLE = 180.0f;

    private final Drawable mDrawable;
    private final RectF mRect;
    private final Path mSectorPath;

    private float mOffsetX;
    private float mOffsetY;

    public SectorDrawable(Drawable drawable) {
        super(drawable, -1, -1);
        mDrawable = drawable;
        mRect = new RectF();
        mSectorPath = new Path();
    }

    public void setCenterOffsetX(float offsetX) {
        mOffsetX = offsetX;
    }

    public void setCenterOffsetY(float offsetY) {
        mOffsetY = offsetY;
    }

    @Override
    public void draw(Canvas canvas) {
        Rect bounds = getBounds();

        int width = bounds.width();
        int height = bounds.height();

        if (width <= 0 || height <= 0) {
            return;
        }

        int level = getLevel();
        if (level < 0) {
            level = 0;
        } else if (level > MAX_LEVEL) {
            level = MAX_LEVEL;
        }

        mRect.set(0, 0, width, height * 2);

        mSectorPath.reset();
        mSectorPath.moveTo(mRect.centerX() + mOffsetX, mRect.centerY() + mOffsetY);
        mSectorPath.arcTo(mRect, START_ANGLE, (float) level / MAX_LEVEL * TOTAL_ANGLE);
        mSectorPath.lineTo(mRect.centerX() + mOffsetX, mRect.centerY() + mOffsetY);
        mSectorPath.close();

        canvas.save();
        canvas.clipPath(mSectorPath);
        mDrawable.draw(canvas);
        canvas.restore();
    }
}
